package com.archerdu.commons.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 文件工具类
 * 
 * @projectName springDemo
 * @description 文件工具类
 * @author archer du
 * @createDate 2013年9月27日 下午5:20:25
 * @updateUser dxf
 * @updateDate 2013年9月27日 下午5:20:25
 * @updateRemark 新建
 * @version 0.0.1
 */
public class FileUtil {

    private static final Log           LOG       = LogFactory.getLog(FileUtil.class);
    public static long                 timePoint = 0L;
    public static long                 inteval   = 20 * 60 * 1000L;
    private static Map<String, String> cache     = new HashMap<String, String>();

    /**
     * 清除缓存
     */
    public static void checkCache() {
        if (System.currentTimeMillis() - timePoint > inteval)
            cache.clear();
    }

    /**
     * 使用指定编码读取文件内容
     * 
     * @param fileName
     * @param encoding
     * @return
     */
    public static String fileToString(String fileName, String encoding) {
        // 清除缓存, 暂时不使用缓存方法，2012-10-08
        // checkCache();

        String result = "";
        // String result= cache.get(fileName);
        // 重新读取文件
        // if(null==result){
        StringBuffer sb = new StringBuffer("");
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), encoding));
            String str = null;
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            br.close();
        } catch (UnsupportedEncodingException e) {
            LOG.error(e.getMessage(), e);
            LOG.error(e.getMessage(), e);
        } catch (FileNotFoundException e) {
            LOG.error(e.getMessage(), e);
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
        result = sb.toString();
        // }
        return result;
    }

    /**
     * 将字符串写到文件
     * 
     * @param src
     *            字符串源
     * @param fileName
     *            文件名
     * @param encoding
     *            编码
     * @param bufferLength
     *            缓存长度
     */
    public static void stringToFile(String src, String fileName, String encoding, int bufferLength) {
        try {
            File file = new File(fileName);
            if (!file.exists())
                file.createNewFile();
            StringReader sr = new StringReader(src);
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), encoding));
            CharBuffer cb = CharBuffer.allocate(bufferLength);
            int n = sr.read(cb);
            while (n != -1) {
                cb.flip();
                bw.write(cb.toString().toCharArray());
                cb.clear();
                n = sr.read(cb);
            }
            bw.close();
            sr.close();
        } catch (UnsupportedEncodingException e) {
            LOG.error(e.getMessage(), e);
        } catch (FileNotFoundException e) {
            LOG.error(e.getMessage(), e);
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }

    /**
     * 读取ulr内容到字符串
     * 
     * @param url
     *            链接地址
     * @param encoding
     *            内容编码
     * @param bufferLength
     *            缓存长度
     * @return
     */
    public static String readUrl(String url, String encoding, int bufferLength) {
        StringBuffer sb = new StringBuffer("");
        try {
            URL _url = new URL(url);
            HttpURLConnection uc = (HttpURLConnection) _url.openConnection();
            InputStream is = uc.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is, encoding));
            CharBuffer cb = CharBuffer.allocate(bufferLength);

            int n = br.read(cb);

            while (n != -1) {
                cb.flip();
                sb.append(cb);
                cb.clear();
                n = br.read(cb);
            }
            br.close();
            is.close();
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
        return sb.toString();
    }

    /**
     * 字节码复制文件，暂时没发现编码问题，复制图片也是可以的
     * 
     * @param src
     *            输入流
     * @param tar
     *            输出流
     * @param bufferLength
     *            缓存长度
     */
    public static void copyByByte(InputStream src, OutputStream tar, int bufferLength) {
        BufferedInputStream bis = new BufferedInputStream(src);
        BufferedOutputStream bos = new BufferedOutputStream(tar);
        try {
            byte[] buffer = new byte[bufferLength];
            int n = bis.read(buffer, 0, bufferLength);
            System.out.println(bis.available());
            while (n != -1) {
                bos.write(buffer, 0, n);
                buffer = new byte[bufferLength];
                n = bis.read(buffer, 0, bufferLength);
            }
            bos.close();
            tar.close();
            bis.close();
            tar.close();
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }

    public static void copyFile(String src, String tar, int bufferLength) throws FileNotFoundException {
        copyByByte(new FileInputStream(src), new FileOutputStream(tar), bufferLength);
    }

    /**
     * 从文件中的字符串逐行读取到列表中
     * 
     * @param fileName
     *            文件名
     * @param encoding
     *            文件编码
     * @param bufferLength
     *            缓存区大小
     * @return
     */
    public static List<String> listFromFile(String fileName, String encoding, int bufferLength) {
        List<String> list = new ArrayList<String>();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), encoding));
            String str = null;
            while ((str = br.readLine()) != null) {
                list.add(str);
            }
            br.close();
        } catch (UnsupportedEncodingException e) {
            LOG.error(e.getMessage(), e);
        } catch (FileNotFoundException e) {
            LOG.error(e.getMessage(), e);
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }

        return list;
    }

    /**
     * 使用默认参数，从文件中的字符串逐行读取到列表中
     * 
     * @param fileName
     *            文件名
     * @return
     */
    public static List<String> listFromFile(String fileName) {
        return listFromFile(fileName, "utf-8", 1024);
    }

    public static String getSuffix(String fileName) {
        if (null == fileName)
            return "";
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }
}
